/**
 * 
 */
package com.swg.cocobox.server;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import com.swg.cocobox.KeyChange;

/**
 * @author satriaprayoga
 *
 */
public abstract class ReaderServer extends Server{
	
	protected ByteBuffer readBuffer=ByteBuffer.allocate(8192);

	public ReaderServer(InetAddress address, int port) throws IOException {
		super(address, port);
	}

	public ReaderServer(String host, int port) throws IOException {
		super(host, port);
	}
	
	@Override
	protected void accept(SelectionKey key) throws IOException {
		ServerSocketChannel channel=(ServerSocketChannel)key.channel();
		SocketChannel socketChannel=channel.accept();
		socketChannel.configureBlocking(false);
		socketChannel.register(selector, SelectionKey.OP_READ);
		
	}
	
	protected abstract void read(SelectionKey key)throws IOException;
	
	@Override
	public void run() {
		while(true){
			try {
				synchronized (keyChanges) {
					Iterator<KeyChange> keyIterator=keyChanges.iterator();
					while(keyIterator.hasNext()){
						KeyChange kc=keyIterator.next();
						switch (kc.getType()) {
						case KeyChange.CHANGE:
							SelectionKey key=kc.getChannel().keyFor(selector);
							key.interestOps(kc.getOperation());
						}
					}
					keyChanges.clear();
				}
				selector.select();
				Iterator<SelectionKey> selectedKeys=selector.selectedKeys().iterator();
				while(selectedKeys.hasNext()){
					SelectionKey key=selectedKeys.next();
					selectedKeys.remove();
					if(!key.isValid()){
						continue;
					}
					if(key.isAcceptable()){
						accept(key);
					}else if(key.isReadable()){
						read(key);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void startServer() {
		// TODO Auto-generated method stub
		
	}

}
